<template>
  <div class="mainContent">
    <div class="contentTwoStep">
      <!-- 第一步 -->
      <div class="pregoss rowFlex allCenter">
        <div class="stepDiv rowFlex allCenter">
          <span class="step">1</span>
          <div class="text">
            <p class="title">剧集信息</p>
            <p class="sub">上传+确认</p>
          </div>
        </div>
        <div class="line"></div>
        <div class="stepDiv rowFlex allCenter">
          <span class="stepLine">2</span>
          <div class="text">
            <p class="title2">提审信息</p>
            <p class="sub">材料+内容</p>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="tableContent">
          <div>
            <el-row
              class="tableHeader rowFlex columnCenter"
              style="padding-left:20px;"
            >
              <el-col :span="2">剧集</el-col>
              <el-col :span="7">文件名称</el-col>
              <el-col :span="5">剧集时长</el-col>
              <el-col :span="6">视频大小</el-col>
              <!-- <el-col :span="3">状态</el-col>
              <el-col :span="4">审核备注</el-col> -->
              <el-col :span="4">操作</el-col>
            </el-row>
          </div>
          <div
            v-if="tableList.length > 0"
            class="tableItemList"
          >
            <!-- 之前有的数据 -->
            <div
              v-for="(item, index) in tableList"
              :key="index"
              class="tableItem"
            >
              <el-row
                class="rowFlex allCenter rowItem"
                style="padding-left:20px;"
              >
                <el-col :span="2">
                  <div class="showScoreEdit">
                    <div
                      v-if="!item.chapter_num_is_input"
                      class="rowFlex columnCenter"
                      @mouseenter="mouseenter(index, 'chapter_num')"
                      @mouseleave="mouseleave(index, 'chapter_num')"
                    >
                      <span class="chapter_title">{{ item.chapter_num }}</span>
                      <div class="iconEdit">
                        <svg-icon
                          v-show="item.chapter_num_is_edit"
                          icon-class="edit2"
                          class="icon"
                          @click="editQualityIcon(index, 'chapter_num')"
                        />
                      </div>
                    </div>
                    <div v-else>
                      <el-input
                        v-model="editProps"
                        clearable
                        style="width: 80px"
                        @blur="blurEditIcon(index, 'chapter_num')"
                        @change="blurEditIcon(index, 'chapter_num')"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="7">
                  <div class="showScoreEdit">
                    <!--  @mouseenter="mouseenter(index, 'chapter_title')" @mouseleave="mouseleave(index, 'chapter_title')" 暂时隐藏 -->
                    <div
                      v-if="!item.chapter_title_is_input"
                      class="rowFlex columnCenter"
                    >
                      <span class="chapter_title">{{ item.chapter_title }}</span>
                      <div class="iconEdit">
                        <svg-icon
                          v-show="item.chapter_title_is_edit"
                          icon-class="edit2"
                          class="icon"
                          @click="editQualityIcon(index, 'chapter_title')"
                        />
                      </div>
                    </div>
                    <div v-else>
                      <el-input
                        v-model="editProps"
                        clearable
                        style="width: 200px"
                        @change="blurEditIcon(index, 'chapter_title')"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="5">{{ item.durationTime }}</el-col>
                <el-col :span="6">{{ Number(item.file_size)?(item.file_size/1024/1024).toFixed(1):0 }}M</el-col>
                <!-- <el-col :span="3">
                  <div v-if="item.audit_status_title && item.audit_status_title!==''">
                    <span :class="`check_status_icon ${item.audit_status == 2 ? 'success' : (item.audit_status == 99 || item.audit_status == 98) ? 'ongoing' : (item.audit_status == 1 ) ? 'error' : '' }`"></span>
                    <span>{{ item.audit_status_title }}</span>
                  </div>
                </el-col> -->
                <!-- <el-col
                  :span="4"
                  class="audit_msg"
                >{{ item.audit_msg }}</el-col> -->
                <el-col
                  :span="4"
                  class="rowFlex columnCenter"
                >
                  <el-button
                    type="text"
                    size="medium"
                    @click="play(item)"
                  >播放</el-button>
                  <div v-if="rowInfo.property_type!=3">
                    <div
                      v-show="!uploadWaiting"
                      @click="againUploadFn(item, index)"
                    >
                      <uploadVideo
                        :again-upload="againUpload"
                        :table-list="tableList"
                        @progress="progress"
                        @resultUpload="resultUpload"
                      >
                        <el-button
                          type="text"
                          size="medium"
                          class="replayUpload"
                        >重新上传</el-button>
                      </uploadVideo>
                    </div>
                    <el-button
                      v-show="uploadWaiting"
                      type="text"
                      size="medium"
                      class="replayUpload"
                      @click="waitUpload"
                    >重新上传</el-button>
                  </div>
                  <!-- <el-popconfirm
                    v-if="rowInfo.property_type!=3"
                    v-permission:upload-delete
                    icon="el-icon-info"
                    icon-color="red"
                    style="margin-left:10px;"
                    title="确定删除吗？"
                    @confirm="del(item, index)"
                  >
                    <el-button
                      slot="reference"
                      type="text"
                      size="medium"
                    >删除</el-button>
                  </el-popconfirm> -->
                </el-col>
              </el-row>
              <el-progress
                v-if="item.progress > 0 && item.progress < 100"
                :percentage="item.progress"
                :text-inside="true"
                :stroke-width="15"
              ></el-progress>
            </div>
            <!-- 新上传的数据 -->
          </div>
          <div v-else>
            <div class="tableItem">
              <el-row class="rowFlex allCenter rowItem">
                <el-col style="text-align:center;">暂无数据</el-col>
              </el-row>
            </div>
          </div>
        </div>

      </div>
      <videoPlay
        v-if="showVideoPlay"
        :ismp4="ismp4"
        :show.sync="showVideoPlay"
        :video-url="playVideoUrl"
      ></videoPlay>
    </div>

    <div class="dialog-footer rowFlex">
      <div class="btns">
        <el-button
          class="btn"
          @click="close"
        >取消</el-button>
        <el-button
          class="btn"
          type="primary"
          :loading="loading"
          @click="nextStep"
        >下一步</el-button>
      </div>
    </div>

  </div>
</template>
<script>
import uploadVideo from '@/common/component/uploadVideo.vue'
import { uploadChapter, idPlayUrl, getSignUrl, delPlaylet, delChapter } from '@/api/content'
import { mapState, mapMutations } from 'vuex'
import { removeDp, getTimeVideo } from '@/utils/index'
import videoPlay from '@/common/component/uploadVideoplay.vue'
export default {
  components: {
    uploadVideo,
    videoPlay
  },
  props: {
    rowInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      uploadWaiting: false, // 上传中
      progressScore: 0,
      editProps: '',
      down_url: '',
      ruleForm: {},
      uploadList: [],
      tableList: [],
      // tableListLength: 0,
      showVideoPlay: false,
      playVideoUrl: '',
      ismp4: false,
      againUpload: false,
      againUploadIndex: {}
    }
  },
  mounted() {
    // this.uploadChapter()
    this.initInfo()
  },
  methods: {
    initInfo() {
      this.ruleForm = {}
      this.initInfo = {}
      if (this.$route.query.id) {
        this.ruleForm = this.rowInfo
        this.ruleForm.id = this.$route.query.id
        if (this.rowInfo.chapterList && this.rowInfo.chapterList.length > 0) {
          this.handleTableList(true)
        }
      } else {
        if (this.rowInfo.id) {
          this.ruleForm = this.rowInfo
          this.handleTableList()
        }
      }
    },
    handleTableList(type) {
      this.rowInfo.chapterList.map((item) => {
        item.uid = item.chapter_id
        item.durationTime = getTimeVideo(item.duration)
        // 只有从上第一步进来的时候拼接
        item.chapter_title.indexOf('-') !== -1 && type ? (item.chapter_title = this.rowInfo.title + '-' + item.chapter_title.split('-')[1]) : ''
      })
      this.tableList = this.rowInfo.chapterList
      console.log(this.tableList, 'this.tableList')
    },
    close() {
      this.$router.push(`${this.$route.path}`)
      this.$emit('cancel')
    },
    startUpload() {
      // this.tableListLength = this.tableList.length
      this.uploadList = []
      this.againUpload = false
    },
    uploadChapter() {
      // 之前只传修改的剧集 新增版本剧的时候 要传入所有的剧集
      let list = []
      if (this.rowInfo.property_type == 2 && this.rowInfo.isCreatePlaylet) {
        // 新增版本剧
        list = this.tableList
      } else {
        list = this.tableList.filter((item) => item.isChange)
      }
      const upload_list = list.map((item) => {
        return {
          chapter_num: item.chapter_num,
          chapter_title: item.chapter_title,
          duration: item.duration,
          down_url: item.down_url,
          file_size: item.file_size,
          chapter_id: this.rowInfo.property_type == 2 && this.rowInfo.isCreatePlaylet ? '' : item.chapter_id || null
        }
      })
      if (upload_list.length === 0) {
        this.$router.push(`${this.$route.path}`)
        this.loading = false
        this.$emit('submit')
        return false
      }
      const data = {
        id: this.ruleForm.playlet_id,
        playlet_audit_id: this.rowInfo.id,
        upload_list
      }
      this.loading = true
      uploadChapter(data).then((res) => {
        this.loading = false
        if (res.status_code === 1) {
          // this.$message.success(res.msg)
          this.$emit('submit')
          this.$router.push(`${this.$route.path}`)
        }
      })
    },
    // 获取播放时长
    getVideoDuration(file, index, name) {
      const videoName = name.split('.')[0]
      return new Promise((resolve, reject) => {
        const url = URL.createObjectURL(file)
        const audioElement = new Audio(url)
        let duration
        const fun = (duration) => {
          this.$set(this.tableList[index], 'duration', duration)
          this.$set(this.tableList[index], 'durationTime', getTimeVideo(Math.floor(duration)))
          this.$set(this.tableList[index], 'chapter_num', videoName.replace(/[^0-9]/gi, ''))
          this.$set(this.tableList[index], 'file', url)
          this.$set(this.tableList[index], 'file_size', Math.floor(file.size))
          this.tableList = this.tableList.concat([])
          resolve(duration)
        }
        // 下面需要注意的是在监听loadedmetadata绑定的事件中对duration直接进行赋值是无效的，需要在fun回调函数中进行赋值
        audioElement.addEventListener('loadedmetadata', function () {
          // 音频/视频的元数据已加载时，会发生 loadedmetadata 事件
          duration = audioElement.duration // 时长以秒作为单位
          fun(parseFloat(duration).toFixed(1))
        })
      })
    },
    progress(list) {
      this.uploadWaiting = true
      this.uploadList = removeDp(this.uploadList, list, 'uid')
      this.uploadList.map((item, index) => {
        item.chapter_title = item.name
        item.isChange = true
        item.duration = 0
      })
      if (!this.againUpload) {
        this.tableList = removeDp(this.tableList, this.uploadList, 'uid')
        // this.tableList = this.tableList.concat(this.uploadList)
      } else {
        // 重新上传
        this.$set(this.tableList[this.againUploadIndex], 'progress', this.uploadList[0].progress)
        this.$set(this.tableList[this.againUploadIndex], 'chapter_title', this.uploadList[0].chapter_title)
        this.$set(this.tableList[this.againUploadIndex], 'name', this.uploadList[0].chapter_title)
        // this.tableList[this.againUploadIndex] = this.uploadList[0]
        this.$forceUpdate()
      }
    },
    waitUpload() {
      this.$message.warning('上传视频中,请稍等')
    },
    async resultUpload(data) {
      console.log(data, this.tableList, '上传完成')
      // this.tableListLength++
      const index = this.tableList.findIndex((item) => item.name === data.name)
      await this.getVideoDuration(data.raw, index, data.name)
      if (this.againUpload) {
        console.log('重新上传')
        this.$set(this.tableList[this.againUploadIndex], 'down_url', data.down_url)
        this.$set(this.tableList[this.againUploadIndex], 'isChange', true)
        this.$set(this.tableList[this.againUploadIndex], 'uid', data.uid)
        this.$set(this.tableList[this.againUploadIndex], 'file', URL.createObjectURL(data.raw))
      }
      // 重置储存的数据
      const indexUrl = this.uploadList.findIndex((item) => item.uid === data.uid)
      this.uploadList.splice(indexUrl, 1)
      // this.tableListLength = this.tableList.length
      this.uploadWaiting = false
      setTimeout(() => {
        this.uploadWaiting = false
        this.uploadList = []
      }, 2000)
    },
    mouseenter(index, prop) {
      if (this.rowInfo.property_type != 3) {
        this.$set(this.tableList[index], prop + '_is_edit', true)
        this.$forceUpdate()
      }
    },
    mouseleave(index, prop) {
      this.$set(this.tableList[index], prop + '_is_edit', false)
      this.$forceUpdate()
    },
    blurEditIcon(index, prop) {
      console.log(index, prop)
      this.$set(this.tableList[index], prop + '_is_input', false)
      this.$set(this.tableList[index], prop + '_is_edit', false)
      this.$set(this.tableList[index], prop, this.editProps)
      this.$set(this.tableList[index], 'isChange', true)
      this.$forceUpdate()
    },
    editQualityIcon(index, prop) {
      this.tableList.map((item) => {
        item.chapter_num_is_input = false
        item.chapter_num_is_edit = false
        item.chapter_title_is_input = false
        item.chapter_title_is_edit = false
      })
      this.$set(this.tableList[index], prop + '_is_input', true)
      this.$forceUpdate()
      this.editProps = this.tableList[index][prop]
    },
    getSameNum(Arr) {
      const result = [] // 用于保存最后的结果
      // 排序
      const arr = Arr.sort(function (a, b) {
        return a.chapter_num - b.chapter_num // increse
      })
      // 由于每次遍历访问Arr.length都是需要重复执行的，因此保存到len，提高效率
      const len = Arr.length
      // 遍历比较，看是否有相同的数字
      for (let i = 0; i < len - 1; i++) {
        if (Arr[i].chapter_num === Arr[i + 1].chapter_num) {
          result.push(Arr[i])
        }
      }
      // 去重，防止有三个相同的时，会多push一个相同数字
      return Array.from(new Set(result))
    },
    // 只上传处理过的数据包括重新上传和新增的 不处理的数据不给后台传递
    nextStep() {
      const noNum = this.tableList.find((item) => Number(item.chapter_num) === 0)
      const noLoad = this.tableList.find((item) => !item.chapter_num)
      const data = this.getSameNum(this.tableList)
      if (data.length > 0) {
        this.$message.warning('剧集名不能相同')
        return
      }
      if (noNum) {
        this.$message.warning('请输入正确的剧集')
        return
      }
      if (noLoad) {
        this.$message.warning('视频上传中...')
        return
      }
      this.uploadChapter()
    },
    play(item) {
      // idPlayUrl, getSignUrl
      console.log(item, '123123')
      if (!item.file) {
        idPlayUrl({ chapter_id: item.chapter_id }).then((res) => {
          if (res.status_code === 1) {
            this.showVideoPlay = true
            this.playVideoUrl = res.data.play_url
            this.playVideoUrl && this.playVideoUrl.indexOf('.mp4') !== -1 ? (this.ismp4 = true) : (this.ismp4 = false)
          }
        })
      } else {
        // 播放本地视频
        this.ismp4 = true
        this.showVideoPlay = true
        this.playVideoUrl = item.file
      }
    },
    againUploadFn(item, index) {
      this.againUpload = true
      this.againUploadIndex = index
    },
    del(item, index) {
      if (item.file) {
        this.tableList.splice(index, 1)
        return false
      }
      // 删除调用接口
      if (this.rowInfo.property_type == 1) {
        // 合同剧可删除和编辑
        delChapter({ chapter_id: item.chapter_id }).then((res) => {
          if (res.status_code === 1) {
            this.$message.success(res.msg)
            this.tableList.splice(index, 1)
          }
        })
      } else if (this.rowInfo.property_type == 2) {
        // 新增的时候版本剧的剧集来自合同剧 不能调接口删除 这时候删除的是合同剧的剧集
        if (this.rowInfo.isCreatePlaylet) {
          // 新增版本剧
          this.tableList.splice(index, 1)
        } else {
          delChapter({ chapter_id: item.chapter_id }).then((res) => {
            if (res.status_code === 1) {
              this.$message.success(res.msg)
              this.tableList.splice(index, 1)
            }
          })
        }
      } else {
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.iconEdit {
  width: 30px;
}
.contentTwoStep {
  width: 980px;
  height: 100%;
  overflow: auto;
  padding-bottom: 80px;
}
.pregoss {
  .stepDiv {
    width: auto;
    height: 80px;
    .step,
    .stepLine {
      width: 32px;
      height: 32px;
      border-radius: 16px;
      background: #06c261;
      font-size: 14px;
      color: #fff;
      text-align: center;
      line-height: 32px;
      margin-right: 10px;
    }
    .stepLine {
      color: rgba(0, 0, 0, 0.15);
      border: 1px solid rgba(0, 0, 0, 0.15);
      background: #fff;
    }
    .text {
      P {
        line-height: 20px;
        margin: 0;
      }
      .title,
      .title2 {
        font-size: 16px;
        font-weight: bolder;
      }
      .title2 {
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: bolder;
      }
      .sub {
        margin-top: 4px;
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: rgba(153, 153, 153, 0.85);
      }
    }
  }
  .line {
    width: 200px;
    height: 1px;
    background: rgba(0, 0, 0, 0.15);
    margin: 0 20px;
  }
}

.content {
  padding: 20px;
  ::v-deep .el-textarea__inner {
    height: 100px;
  }
}
.chooseUpload {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 20px;
}
.showScoreEdit {
  width: 100%;
  height: 100%;
  cursor: pointer;
  .icon {
    margin-left: 10px;
  }
}
.replayUpload {
  position: relative;
  margin: 0 10px;
}
.tableContent {
  width: 100%;
  height: auto;
  color: #909399;
  margin-bottom: 20px;
  font-weight: 500;
  .el-col {
    text-align: left;
  }
  .tableHeader {
    border-color: gray;
    background: #f7f8fa;
    width: 100%;
    height: 40px;
    border-bottom: 1px solid #ebeef5;
    .el-col {
      color: #333333;
      border: bolder;
    }
  }
  .tableItem {
    line-height: 60px;
    border-bottom: 1px solid #ebeef5;
    padding: 10px 0;
    .rowItem {
      min-height: 60px;
    }
    .audit_msg {
      line-height: 20px;
      padding-right: 20px;
    }
  }
  .chapter_title {
    min-width: 30px;
    min-height: 20px;
    line-height: 20px;
    padding-right: 20px;
    word-break: break-all;
  }
}
.mainContent {
  height: 100%;
  position: relative;
}
</style>
